package cai;

import org.apache.http.Consts;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.net.URLEncoder;
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Collectors;

public class HttpCustomUtil {

	/**
	 * dyh add
	 * 发生Get请求
	 * @param url 请求地址
	 * @param headerMap	请求头参数
	 * @param parameterMap	请求参数
	 * @param connectTimeout	超时时间(毫秒)
	 * @return
	 * @throws Exception
	 */
	public static String sendGet(String url, Map<String, String> headerMap, IdentityHashMap<String, String> parameterMap, Integer connectTimeout) throws Exception {
		URIBuilder uriBuilder = new URIBuilder(url);
		if (parameterMap != null) {
			for (String key : parameterMap.keySet()) uriBuilder.addParameter(key, parameterMap.get(key)); //转换为路径参数
		}

		Builder custom = RequestConfig.custom();
		if(connectTimeout != null) custom.setConnectTimeout(connectTimeout);

		HttpGet http = new HttpGet(uriBuilder.build());
		http.setConfig(custom.build());
		if(headerMap != null) { //请求头参数
			for (Entry<String, String> entry : headerMap.entrySet()) http.setHeader(entry.getKey(), URLEncoder.encode(entry.getValue(), "UTF-8"));    //请求头参数设置
		}
		return HttpCustomUtil.sendRequest(http);
	}
	
	
	/**
	 * application/json 请求
	 * @param url		请求地址
	 * @param headerMap	请求头参数
	 * @param dataJson	请求参数
	 * @return
	 * @throws Exception
	 */
	public static String sendPostJson(String url, Map<String, String> headerMap, String dataJson) throws Exception {
		
		StringEntity entityStr = new StringEntity(dataJson, ContentType.create("application/json", Consts.UTF_8));
				
		//配置
		 RequestConfig config = RequestConfig.custom()
				 .setConnectTimeout(10000) //超时时间
				 .build();
		 
		 HttpPost http = new HttpPost(url);//Post请求
		 http.setConfig(config);//配置赋值
		 http.setEntity(entityStr);//post参数传输
		 //http.setHeader("Content-Type", "application/json; charset=utf-8");
		 
		 if(headerMap != null) {
				for (Entry<String, String> entry : headerMap.entrySet())
					http.setHeader(entry.getKey(), entry.getValue());    //请求头参数设置
		 }
		return HttpCustomUtil.sendRequest(http);
	}
	
	//发生请求
	public static String sendRequest(HttpRequestBase httpRequest) throws Exception{
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		try {
			httpClient = HttpClients.createDefault();	//创建http连接
			response = httpClient.execute(httpRequest); //执行
		    int status = response.getStatusLine().getStatusCode();	
		   if(status == HttpStatus.SC_OK) {
			   return EntityUtils.toString(response.getEntity(), "UTF-8").replaceAll("\\s*|\t|\r|\n", ""); //返回结果集
		   }else {	   
			   //log.error("error {} status {}", httpRequest.getURI(), status);
			   throw new RuntimeException("error: " + httpRequest.getURI() + ", http-status: " + status);
		   }
		   
		} catch (Exception e) {
			throw e;
		}finally {
			if(response != null) response.close();
			if(httpClient != null) httpClient.close();
		}
	}
	
	public static void main(String[] args) throws Exception {
//		String url = "http://10.1.90.41:19127/qualityComment/queryJvmMemory";
//
//		Map<String, String> headerMap = new HashMap<>();
//		headerMap.put("iscUserId", "fdsdwew_iscUserId");
//		headerMap.put("token", "token");
//
//		IdentityHashMap<String, String> parameterMap = new IdentityHashMap<>();
//		parameterMap.put(new String("id"), "11");
//		parameterMap.put(new String("name"), "段永红");
//
//		String get = HttpUtil.sendGet(url, headerMap, parameterMap, 10000);
//		System.out.println("get = " + get);

		try {
			Method method = HttpCustomUtil.class.getMethod("sendGet", String.class, Map.class, IdentityHashMap.class, Integer.class);

			Parameter[] params = method.getParameters();
			List<String> paramNames = Arrays.asList(params).stream().map(m -> m.getName()).collect(Collectors.toList());

			System.out.println("方法名: " +  method.getName());
			System.out.println("参数数量: " +  method.getParameterCount());
			System.out.println("参数类型: " +  Arrays.asList(method.getParameterTypes()));
			System.out.println("参数名称: " +  paramNames);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
